/**
 * 
 */
package absolute_zero.com.urbox;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import android.util.Log;

/**
 * @author Maliek Mcknight
 * 
 */
public class MethodCall {

	public static String CreateMethod(String method,
			HashMap<String, String> parameters, boolean needs_sig) {

		String URL = "http://droidweb.com/scripts/urbox.php?";
		String next;
		Set<String> keyset = parameters.keySet();
		Iterator<String> method_parameters = keyset.iterator();
		try {
			while (method_parameters.hasNext()) {
				next = method_parameters.next();
				URL = URL + "&" + next + "="
						+ URLEncoder.encode(parameters.get(next), "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			return "Error in encoding";
		}
		if (needs_sig) {
			String signature = "";
			// alphabetize methods
			List<String> methods = new ArrayList<String>(parameters.keySet());
			Collections.sort(methods);
			Iterator<String> alphabetized_method_parameters = methods
					.iterator();
			// Collect alphabetized parameters and values
			while (alphabetized_method_parameters.hasNext()) {
				next = alphabetized_method_parameters.next();
				signature = signature + next + parameters.get(next);
			}
			try {
				// MD5 hash signatures
				signature = MD5.MD5(signature);
			} catch (NoSuchAlgorithmException e) {

			} catch (UnsupportedEncodingException f) {

			}
			URL = URL + "&" + "api_sig=" + signature;

		}
		Log.d("url", URL);
		return URL;
	}

}
